import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

//引用vue-router插件
Vue.use(VueRouter)
//引入store实例
import store from '@/store'
//重写vue-router中push / replace方法
let orginPush = VueRouter.prototype.push;
let orginReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function(location,resolve,reject){
    if(resolve && reject){
        orginPush.call(this,location,resolve,reject);
    }else{
        orginPush.call(this,location,()=>{},()=>{});
    }
}
VueRouter.prototype.replace = function(location,resolve,reject){
    if(resolve && reject){
        orginReplace.call(this,location,resolve,reject);
    }else{
        orginReplace.call(this,location,()=>{},()=>{});
    }
}
//路由信息
const router = new VueRouter({
    routes,
    mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return { y : 0 }
      },
});
router.beforeEach(async(to,from,next) =>{
    let token = store.state.user.token;
    let name =store.state.user.userinfo.name;
    console.log(token)
    //检查是否有token，没有的话，进入login重新登录
    if(token){
        if(to.path=='/login'){
            next('/home')
        }else{
            //避免刷新将 name--userinfo信息丢失
            if(name){
                next()
            }else{
                //用户信息丢失，重新获取信息，action发请求
                try {
                    await store.dispatch('userInfo');
                    next()
                } catch (error) {
                    await store.dispatch('userLogout');
                    next('/login')
                }
            }
        }
    }else{
        //用户未登录，处理点击情况
        let toPath = to.path;
        if(toPath.indexOf('/trade') !=-1 ||toPath.indexOf('/pay') !=-1||toPath.indexOf('/center') !=-1)
        {
            next('/login?redirect=' + toPath)
        }else{
            next()
        }
    }
})
export default router